package com.baijiayun.sdk.util;

import com.baijiayun.sdk.model.BaseRequest;
import com.google.common.base.CaseFormat;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 签名工具
 */
public class SignUtils {
    private static Logger logger = LoggerFactory.getLogger(SignUtils.class);

    /**
     * 签名
     *
     * @return
     */
    public static String getSign(Object obj, String partnerKey) throws IllegalAccessException {
        List<Field> baseFields = new ArrayList();
        Field[] fields = obj.getClass().getDeclaredFields();
        Map<String, Object> treeMap = new TreeMap<>();
        Class tempClass = BaseRequest.class;
        while (tempClass != null) {//当父类为null的时候说明到达了最上层的父类(Object类).
            baseFields.addAll(Arrays.asList(tempClass.getDeclaredFields()));
            tempClass = tempClass.getSuperclass(); //得到父类,然后赋给自己
        }
        // 遍历父级字段
        for (Field field : baseFields) {
            RequestParamsUtils.putFieldToMap(field, treeMap, obj);
        }
        // 遍历当前类的字段
        for (Field field : fields) {
            RequestParamsUtils.putFieldToMap(field, treeMap, obj);
        }
        return sign(treeMap, partnerKey);
    }

    /**
     * 签名
     *
     * @return
     */
    public static String sign(Map<String, Object> params, String partnerKey) {
        StringBuilder paramStringBuilder = new StringBuilder(5 * params.size());
        Set<Map.Entry<String, Object>> paramSet = params.entrySet();
        for (Map.Entry<String, Object> entry : paramSet) {
            paramStringBuilder.append(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, entry.getKey())).append("=").append(entry.getValue()).append("&");
        }
        paramStringBuilder.append("partner_key=").append(partnerKey);
        String md5 = DigestUtils.md5Hex(paramStringBuilder.toString());
        return md5.toLowerCase();
    }
}
